import { Singleton } from 'decorates';

export type User = {
  id: string,
  name: string,
  username: string,
  token: string,
  authorized: boolean,
  timestamp: number
}

/**
 * keystone 服务
 * 专用于存储用户身份信息、tonken等信息
 */
@Singleton()
export default class KeystoneService {
  private token_ = '';
  public get token () {
    return this.token_;
  }

  public set token (v: string) {
    this.token_ = v;
  }

  private user_: User = {} as User;
  public get user () {
    return this.user_;
  }

  public set user (v: User) {
    this.user_ = v;
  }

  /**
   * 从缓存中加载认证凭信
   * @returns 成功返回 `true`
   */
  public load () {
    if (!sessionStorage || !sessionStorage.getItem) {
      this.token = '_';
      this.user = {} as User;
      return false;
    }
    const userString = sessionStorage.getItem('user');
    try {
      const user = JSON.parse(userString as string);
      if (user) {
        this.token = user.token;
        this.user = user;
        return true;
      } else {
        this.token = '_';
        this.user = {} as User;
        return false;
      }
    } catch {
      this.token = '_';
      this.user = {} as User;
      return false;
    }
  }

  /**
   * 存储用户信息
   * @param user - 用户信息
   */
  public store (user: Any) {
    sessionStorage.setItem('user', JSON.stringify(user));
  }

  /**
   * 删除本地信息
   * @param key - 本地信息的key
   */
  public remove () {
    sessionStorage.removeItem('user');
    this.token = '_';
    this.user = {} as User;
  }
}
